import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { RbacRole } from './rbac_user/entities/rbac_role.entity';
import { Reflector } from '@nestjs/core';

declare module 'express' {
  interface Request {
    userObj: {
      username: string,
      roles: RbacRole[]
    }
  }
}

@Injectable()
export class RbacLoginGuard implements CanActivate {

  @Inject(JwtService)
  private jwtService: JwtService

  @Inject(Reflector)
  private reflector: Reflector

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {

    const requireLogin = this.reflector.getAllAndOverride('require-login', [
      context.getClass(),
      context.getHandler()
    ])
    if (!requireLogin) {
      return true
    }

    const request: Request = context.switchToHttp().getRequest()
    const authorization = request.header('authorization') || '';
    if(!authorization) {
      throw new UnauthorizedException('用户未登录');
    }
    try {
      const token = authorization.split(' ')[1]
      const data = this.jwtService.verify(token)
      request.user = data.user
      return true
    } catch (error) {
      throw new UnauthorizedException('token 失效，请重新登录');
    }
  }
}
